package com.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 90. 子集 II
 * 递归法实现子集枚举
 *
 * @author fy
 * @date 2022/4/29 11:53
 */
public class Solution90 {

    private List<List<Integer>> res;
    private List<Integer> preList;
    private boolean[] isUsed;

    public List<List<Integer>> subsetsWithDup(int[] nums) {
        int n = nums.length;
        isUsed = new boolean[n];
        res = new ArrayList<>();
        preList = new ArrayList<>();
        // 先对元素排序, 然后当有多个相同元素时跳过
        Arrays.sort(nums);
        // 根据需要元素的次数, 依次递归调用
        for (int count = 0; count <= n; count++) {
            dfs(nums, count, 0);
        }
        return res;
    }

    private void dfs(int[] nums, int count, int index) {
        if (count == 0) {
            res.add(new ArrayList<>(preList));
            return;
        }
        for (int i = index; i < nums.length - count + 1; i++) {
            if (i > 0 && !isUsed[i - 1] && !isUsed[i] && nums[i - 1] == nums[i]) {
                continue;
            }
            isUsed[i] = true;
            preList.add(nums[i]);
            dfs(nums, count - 1, i + 1);
            preList.remove(preList.size() - 1);
            isUsed[i] = false;
        }
    }


    public static void main(String[] args) {
        int[] nums = new int[]{1, 2, 2};
        List<List<Integer>> res = new Solution90().subsetsWithDup(nums);
        System.out.println(res);
    }

}
